<?php 

namespace IMT\OAuthServerBundle\Controller;

use IMT\OAuthServerBundle\Form\Handler\AuthorizeFormHandler;

use IMT\OAuthServerBundle\Form\Type\AuthorizeFormType;

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use FOS\OAuthServerBundle\Controller\AuthorizeController as BaseAuthorizeController;
use IMT\OAuthServerBundle\Form\Model\Authorize;
use IMT\OAuthServerBundle\Document\Client;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class AuthorizeController extends BaseAuthorizeController
{
	public function authorizeAction(Request $request)
	{
		if (!$request->get('client_id')) {
			throw new NotFoundHttpException("Client id parameter {$request->get('client_id')} is missing.");
		}

		$clientManager = $this->container->get('fos_oauth_server.client_manager.default');
		$client = $clientManager->findClientByPublicId($request->get('client_id'));

		if (!($client instanceof \IMT\OAuthServerBundle\Entity\Client)) {
			throw new NotFoundHttpException("Client {$request->get('client_id')} is not found.");
		}

		$user = $this->container->get('security.context')->getToken()->getUser();

		$form = $this->container->get('form.factory')->create(new AuthorizeFormType());
		//$form = $this->container->get('imt_oauth_server.authorize.form');
		$formHandler = new AuthorizeFormHandler($form, 
			$request,  
			$this->container->get('security.context'), 
			$this->container->get('fos_oauth_server.server')
		);

		$authorize = new Authorize();

		if (($response = $formHandler->process($authorize)) !== false) {
			return $response;
		}

		return $this->container->get('templating')->renderResponse('IMTOAuthServerBundle:Authorize:authorize.html.twig', array(
				'form' => $form->createView(),
				'client' => $client,
		));
	}
}
